# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(stringr)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- opt$i
if (!file.exists(fileName)) {
  quit(status = 0)
}

data <- read_tsv(fileName) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  column_to_rownames("SampleID") %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame()

x <- data %>% select(-c("ClassNote"))
y <- data$ClassNote

configJson <- fromJSON(opt$config)
configJson
ntree <- configJson$ntree %>%
  as.numeric()
hasMtry <- configJson$hasMtry %>%
  as.logical()
mtry <- if (hasMtry) {
  configJson$mtry %>%
    as.numeric()
}else {
  if (!is.null(y) && !is.factor(y))
    max(floor(ncol(x) / 3), 1) else floor(sqrt(ncol(x)))
}
hasNodesize <- configJson$hasNodesize %>%
  as.logical()
nodesize <- if (hasNodesize) {
  configJson$nodesize %>%
    as.numeric()
}else {
  if (!is.null(y) && !is.factor(y)) 5 else 1
}
hasMaxnode <- configJson$hasMaxnode %>%
  as.logical()
maxnodes <- if (hasMaxnode) {
  configJson$maxnodes %>%
    as.numeric()
}else {
  NULL
}

replace <- configJson$replace  %>%
  as.logical()
rfRs <- randomForest(x, y, importance = T, proximity = TRUE, ntree = ntree, mtry = mtry, replace = replace,
                     nodesize = nodesize)

importance <- rfRs$importance %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  select(c("Metabolite", "MeanDecreaseGini")) %>%
  arrange(desc(MeanDecreaseGini))
importance
write.csv(importance, "RF_Imp_Rank.csv", row.names = F)












